/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.upgrade.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.DocumentInternalRpcService;
import com.je.common.base.service.rpc.UpgradeModulePackageRpcService;
import com.je.common.base.upgrade.PackageResult;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.exception.UpgradeException;
import com.je.meta.service.upgrade.UpgradeService;
import com.je.meta.util.enumUtil.UpgradeFilePathEnum;
import com.je.meta.util.enumUtil.UpgradeInstallStateEnum;
import com.je.servicecomb.RpcSchemaFactory;
import org.apache.servicecomb.provider.pojo.RpcReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static com.je.servicecomb.JECloud.*;

@Service
public class UpgradeServiceImpl implements UpgradeService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private UpgradeModulePackageRpcService metaUpgradeModulePackageRpcService;
    @RpcReference(microserviceName = "rbac",schemaId = "upgradeModulePackageRpcService")
    private UpgradeModulePackageRpcService rbacUpgradeModulePackageRpcService;
    @RpcReference(microserviceName = "workflow",schemaId = "upgradeModulePackageRpcService")
    private UpgradeModulePackageRpcService workflowUpgradeModulePackageRpcService;

    @Autowired
    private DocumentInternalRpcService documentInternalRpcService;
    @Override
    public void insertPackageFuncs(String upgradeId, String funcIds) {
        List<String> funcIdList = new ArrayList<>(Splitter.on(",").splitToList(funcIds));
        List<DynaBean> funcBeanList = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder()
                .in("JE_CORE_FUNCINFO_ID",funcIdList));

       deleteResourceByType(upgradeId,"func");
        for (DynaBean eachFuncBean : funcBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE",false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME","功能");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE","func");
            detailBean.set("UPGRADERESOURCE_CONTENT_BM",eachFuncBean.getStr("FUNCINFO_FUNCCODE"));
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME",eachFuncBean.getStr("FUNCINFO_FUNCNAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE",eachFuncBean.getStr("JE_CORE_FUNCINFO_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID",upgradeId);
            detailBean.set("UPGRADERESOURCE_REMARK",eachFuncBean.getStr("FUNCINFO_FUNCREMARK"));
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public void insertPackageTables(String upgradeId, String tableIds) {
        List<String> tableIdList = new ArrayList<>(Splitter.on(",").splitToList(tableIds));
        List<DynaBean> tableBeanList = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder()
                .in("JE_CORE_RESOURCETABLE_ID",tableIdList));

        deleteResourceByType(upgradeId,"table");
        for (DynaBean eachTableBean : tableBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE",false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME","资源表");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE","table");
            detailBean.set("UPGRADERESOURCE_CONTENT_BM",eachTableBean.getStr("RESOURCETABLE_TABLECODE"));
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME",eachTableBean.getStr("RESOURCETABLE_TABLENAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE",eachTableBean.getStr("JE_CORE_RESOURCETABLE_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID",upgradeId);
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public void insertPackageDictionarys(String upgradeId, String dictionaryIds) {
        List<String> dictionaryIdList = new ArrayList<>(Splitter.on(",").splitToList(dictionaryIds));
        List<DynaBean> dictionaryBeanList = metaService.select("JE_CORE_DICTIONARY", ConditionsWrapper.builder()
                .in("JE_CORE_DICTIONARY_ID", dictionaryIdList).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));

        deleteResourceByType(upgradeId,"dictionary");
        for (DynaBean eachDictionaryBean : dictionaryBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE", false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME", "数据字典");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE", "dictionary");
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME", eachDictionaryBean.getStr("DICTIONARY_DDNAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE", eachDictionaryBean.getStr("JE_CORE_DICTIONARY_ID"));
            detailBean.set("UPGRADERESOURCE_CONTENT_BM", eachDictionaryBean.getStr("DICTIONARY_DDCODE"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID", upgradeId);
            detailBean.set("UPGRADERESOURCE_CODE", eachDictionaryBean.getStr("DICTIONARY_DDCODE"));
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public void insertPackageGlobalScripts(String upgradeId, String scriptIds) {
        List<String> scriptIdList = new ArrayList<>(Splitter.on(",").splitToList(scriptIds));
        List<DynaBean> scriptBeanList = metaService.select("JE_CORE_COMMJS", ConditionsWrapper.builder()
                .in("JE_CORE_COMMJS_ID", scriptIdList));

        deleteResourceByType(upgradeId,"globalScript");

        for (DynaBean eachScriptBean : scriptBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE", false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME", "全局程序");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE", "globalScript");
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME", eachScriptBean.getStr("COMMJS_FFT"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE", eachScriptBean.getStr("JE_CORE_COMMJS_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID", upgradeId);
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public void insertPackageSystemVariables(String upgradeId, String variableIds) {
        List<String> variableIdList = new ArrayList<>(Splitter.on(",").splitToList(variableIds));
        List<DynaBean> scriptBeanList = metaService.select("JE_CORE_CONFIG", ConditionsWrapper.builder()
                .in("JE_CORE_CONFIG_ID", variableIdList));

       deleteResourceByType(upgradeId,"variable");

        for (DynaBean eachScriptBean : scriptBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE", false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME", "系统变量");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE", "variable");
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME", eachScriptBean.getStr("CONFIG_NAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE", eachScriptBean.getStr("JE_CORE_CONFIG_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID", upgradeId);
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public void insertPackageBusinessData(String upgradeId, String tableIds) {
        List<String> tableIdList = new ArrayList<>(Splitter.on(",").splitToList(tableIds));
        List<DynaBean> tableBeanList = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder()
                .in("JE_CORE_RESOURCETABLE_ID",tableIdList));

        deleteResourceByType(upgradeId,"business");
        for (DynaBean eachTableBean : tableBeanList) {
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE",false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME","业务数据");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE","business");
            detailBean.set("UPGRADERESOURCE_CONTENT_BM",eachTableBean.getStr("RESOURCETABLE_TABLECODE"));
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME",eachTableBean.getStr("RESOURCETABLE_TABLENAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE",eachTableBean.getStr("JE_CORE_RESOURCETABLE_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID",upgradeId);
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public PackageResult doPackage(DynaBean upgradeBean) {
        String prodcutId = upgradeBean.getStr("SY_PRODUCT_ID");
        DynaBean prodcutBean = metaService.selectOneByPk("JE_PRODUCT_MANAGE",prodcutId);
        if(prodcutBean == null){
            throw new UpgradeException(MessageUtils.getMessage("upgrade.product.notExits"));
        }
        PackageResult metaPackageResult = metaUpgradeModulePackageRpcService.packageModule(upgradeBean);
        PackageResult rbacPackageResult = rbacUpgradeModulePackageRpcService.packageModule(upgradeBean);
        PackageResult workflowPackageResult = workflowUpgradeModulePackageRpcService.packageModule(upgradeBean);
        PackageResult mergeAllPackageResult = new PackageResult();
        mergeAllPackageResult.setUpgrade(upgradeBean);
        mergeAllPackageResult.setProduct(prodcutBean);
        mergeAllPackageResult.setProductFunctions(metaPackageResult.getProductFunctions());
        mergeAllPackageResult.setProductTables(metaPackageResult.getProductTables());
        mergeAllPackageResult.setProductDictionarys(metaPackageResult.getProductDictionarys());
        mergeAllPackageResult.setProductSystemVariables(metaPackageResult.getProductSystemVariables());
        mergeAllPackageResult.setProductSystemSettings(metaPackageResult.getProductSystemSettings());
        mergeAllPackageResult.setProductPartols(metaPackageResult.getProductPartols());
        mergeAllPackageResult.setProductReports(metaPackageResult.getProductReports());
        mergeAllPackageResult.setProductCharts(metaPackageResult.getProductCharts());
        mergeAllPackageResult.setProductDataSource(metaPackageResult.getProductDataSource());
        mergeAllPackageResult.setGlobalScripts(metaPackageResult.getGlobalScripts());

        //rbac
        mergeAllPackageResult.setProductRoles(rbacPackageResult.getProductRoles());
        mergeAllPackageResult.setProductMenus(rbacPackageResult.getProductMenus());
        mergeAllPackageResult.setProductTopMenus(rbacPackageResult.getProductTopMenus());
        //工作流
        mergeAllPackageResult.setProductWorkflows(workflowPackageResult.getProductWorkflows());
        //打包业务数据
        Map<String,String> businessMap = (Map<String,String>) upgradeBean.get("businessMap");
        Map<String,List<DynaBean>> businessDataMap=new HashMap<>();
        if (PRODUCT_CORE_META.equals(prodcutBean.getStr("PRODUCT_CODE"))) {
            businessDataMap =  metaUpgradeModulePackageRpcService.packageBusinessData(businessMap);
        }else if(PRODUCT_CORE_WORKFLOW.equals(prodcutBean.getStr("PRODUCT_CODE"))){
            businessDataMap = workflowUpgradeModulePackageRpcService.packageBusinessData(businessMap);
        }else if(PRODUCT_CORE_RBAC.equals(prodcutBean.getStr("PRODUCT_CODE"))){
            businessDataMap = rbacUpgradeModulePackageRpcService.packageBusinessData(businessMap);
        }else {
            UpgradeModulePackageRpcService upgradeModulePackageRpcService = RpcSchemaFactory.getRemoteProvierClazz(prodcutBean.getStr("PRODUCT_CODE"),
                    "upgradeModulePackageRpcService", UpgradeModulePackageRpcService.class);
            businessDataMap = upgradeModulePackageRpcService.packageBusinessData(businessMap);
        }
        mergeAllPackageResult.setBusinessDataMap(businessDataMap);
        return mergeAllPackageResult;
    }

    @Override
    public String doInstall(String pkValue, String fileKey) {
        File file = documentInternalRpcService.readFile(fileKey);
        if(file==null){
            throw new UpgradeException(MessageUtils.getMessage("upgrade.file.notExits"));
        }
        String json  = getcontentJson(file);
        PackageResult packageResult = JSON.parseObject(json,PackageResult.class);
        packageResult.setInstallPackageId(pkValue);

        metaUpgradeModulePackageRpcService.installModule(packageResult);
        rbacUpgradeModulePackageRpcService.installModule(packageResult);
        workflowUpgradeModulePackageRpcService.installModule(packageResult);
        /**
         *更新安装包
         */
        DynaBean dynaBean = new DynaBean("JE_META_UPGRADEINSTALL",false);
        dynaBean.setStr("UPGRADEINSTALL_INSTALL_TIME", DateUtils.formatDateTime(new Date()));
        dynaBean.setStr("UPGRADEINSTALL_INSTALL_CODE", UpgradeInstallStateEnum.INSTALL.getValue());
        dynaBean.setStr("UPGRADEINSTALL_INSTALL_NAME",UpgradeInstallStateEnum.INSTALL.getName());
        dynaBean.setStr("UPGRADEINSTALL_REMARK",packageResult.getUpgrade().getStr("UPGRADEPACKAGE_REMARK"));
        commonService.buildModelModifyInfo(dynaBean);
        metaService.update(dynaBean,ConditionsWrapper.builder().eq("JE_META_UPGRADEINSTALL_ID",pkValue));
        return null;
    }

    private String getcontentJson(File file) {
        try {
            ZipFile zipFile = new ZipFile(file, Charsets.UTF_8);
            ZipEntry zipEntry = zipFile.getEntry(UpgradeFilePathEnum.CONTENT.getPath());
            return IoUtil.read(IoUtil.toStream(IoUtil.readBytes(zipFile.getInputStream(zipEntry))), Charsets.UTF_8);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 1.检查数据库表
     * 2.检查资源表的code和功能code是否重复
     * 3.在插入用户数据时检查表是否存在
     * @param pkValue
     * @return
     */
    @Override
    public String doCheck(String pkValue) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_META_UPGRADEINSTALL",pkValue);
        String fileKey = dynaBean.getStr("UPGRADEINSTALL_FILE_KEY");
        File file = documentInternalRpcService.readFile(fileKey);
        String json  = getcontentJson(file);
        PackageResult packageResult = JSON.parseObject(json,PackageResult.class);
        packageResult.setInstallPackageId(pkValue);
        String result ="";
        result = metaUpgradeModulePackageRpcService.doCheck(packageResult);
        if(StringUtil.isNotEmpty(result)){
            return result;
        }
        result = rbacUpgradeModulePackageRpcService.doCheck(packageResult);
        if(StringUtil.isNotEmpty(result)){
            return result;
        }
        return null;
    }

    @Override
    public void doSave(DynaBean dynaBean) {
        String fileKey =dynaBean.getStr("UPGRADEINSTALL_FILE_KEY");
        File file = documentInternalRpcService.readFile(fileKey);
        if(file==null){
            throw new UpgradeException(MessageUtils.getMessage("upgrade.file.notExits"));
        }
        String json  = getcontentJson(file);
        PackageResult packageResult = JSON.parseObject(json,PackageResult.class);
        DynaBean upgrade = packageResult.getUpgrade();
        dynaBean.setStr("UPGRADEINSTALL_PACKAGE_TIME",upgrade.getStr("UPGRADEPACKAGE_PACKAGE_TIME"));
        dynaBean.set("UPGRADEINSTALL_VERSION",upgrade.getStr("UPGRADEPACKAGE_VERSION"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name",dynaBean.getStr("UPGRADEINSTALL_NAME"));
        jsonObject.put("fileKey",dynaBean.getStr("UPGRADEINSTALL_FILE_KEY"));
        dynaBean.setStr("UPGRADEINSTALL_PACKAGE_FILE",jsonObject.toJSONString());
        dynaBean.setStr("UPGRADEINSTALL_INSTALL_CODE",UpgradeInstallStateEnum.NOINSTALL.getValue());
        dynaBean.setStr("UPGRADEINSTALL_INSTALL_NAME",UpgradeInstallStateEnum.NOINSTALL.getName());
        dynaBean.setStr("JE_META_UPGRADEPACKAGE_ID",upgrade.getStr("JE_META_UPGRADEPACKAGE_ID"));
        dynaBean.setStr("SY_PRODUCT_ID",upgrade.getStr("SY_PRODUCT_ID"));
        dynaBean.setStr("SY_PRODUCT_NAME",upgrade.getStr("SY_PRODUCT_NAME"));
        commonService.buildModelCreateInfo(dynaBean);
        metaService.insert(dynaBean);
    }

    @Override
    public String importDictionaryFromFuncinfo(String upgradeId) {
        /**
         * 1.获取功能的所有字典code
         * 2.对比已导入升级包的字典，存在则去除
         * 3.根据字典codes查找字典表，不为空则存入升级包中
         */
        String result="";
        List<DynaBean> funcs = metaService.select("JE_META_UPGRADERESOURCE",ConditionsWrapper.builder()
                .eq("JE_META_UPGRADEPACKAGE_ID",upgradeId)
                .eq("UPGRADERESOURCE_TYPE_CODE","func"));
        if(funcs==null || funcs.size()==0){
            return MessageUtils.getMessage("upgrade.not.found.dictionary");
        }
        Set<String> ddCodes = new HashSet();
        for(DynaBean fun:funcs){
            String funcId =fun.getStr("UPGRADERESOURCE_CONTENT_CODE");
            List<DynaBean> fields = metaService.select("JE_CORE_RESOURCEFIELD",ConditionsWrapper.builder()
                    .eq("RESOURCEFIELD_FUNCINFO_ID",funcId)
                    .in("RESOURCEFIELD_XTYPE","cbbfield","rgroup","cgroup","cbbfield","treessfield","treessareafield","cbblistfield"));
            for(DynaBean field:fields){
                String configInfo = field.getStr("RESOURCEFIELD_CONFIGINFO");
                if (StringUtil.isNotEmpty(configInfo)) {
                    ddCodes.add(configInfo.split(",")[0]);
                }
            }
        }
        if(ddCodes==null || ddCodes.size()==0){
           return MessageUtils.getMessage("upgrade.not.found.dictionary.in.the.funcion");
        }
        //查找已导入到升级包的字典
        Map<String, String> source = metaService.selectSql(
                "select JE_META_UPGRADEPACKAGE_ID,UPGRADERESOURCE_CONTENT_CODE,UPGRADERESOURCE_CONTENT_BM from JE_META_UPGRADERESOURCE " +
                        "where  JE_META_UPGRADEPACKAGE_ID = {0} AND UPGRADERESOURCE_TYPE_CODE='dictionary' ", upgradeId)
                .stream().collect(Collectors.toMap(p -> String.valueOf(p.get("UPGRADERESOURCE_CONTENT_BM")), p -> String.valueOf(p.get("JE_META_UPGRADEPACKAGE_ID"))));

        List<DynaBean> dicts = metaService.select("JE_CORE_DICTIONARY",ConditionsWrapper.builder()
                .in("DICTIONARY_DDCODE",ddCodes).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
        for(DynaBean dict:dicts){
            String ddCode = dict.getStr("DICTIONARY_DDCODE");
            if(source.containsKey(ddCode)){
                continue;
            }
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE", false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME", "数据字典");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE", "dictionary");
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME", dict.getStr("DICTIONARY_DDNAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE", dict.getStr("JE_CORE_DICTIONARY_ID"));
            detailBean.set("UPGRADERESOURCE_CONTENT_BM", dict.getStr("DICTIONARY_DDCODE"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID", upgradeId);
            detailBean.set("UPGRADERESOURCE_CODE", dict.getStr("DICTIONARY_DDCODE"));
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
        return result;
    }

    @Override
    public String importTableByFuncinfo(String upgradeId) {
        String result="";
        List<DynaBean> funcs = metaService.select("JE_META_UPGRADERESOURCE",ConditionsWrapper.builder()
                .eq("JE_META_UPGRADEPACKAGE_ID",upgradeId)
                .eq("UPGRADERESOURCE_TYPE_CODE","func"));

        if(funcs==null){
            return MessageUtils.getMessage("upgrade.funcResource.notExits");
        }

        Map<String, String> source = metaService.selectSql(
                "select JE_META_UPGRADEPACKAGE_ID,UPGRADERESOURCE_CONTENT_CODE,UPGRADERESOURCE_CONTENT_BM from JE_META_UPGRADERESOURCE " +
                        "where  JE_META_UPGRADEPACKAGE_ID = {0} AND UPGRADERESOURCE_TYPE_CODE='table' ", upgradeId)
                .stream().collect(Collectors.toMap(p -> String.valueOf(p.get("UPGRADERESOURCE_CONTENT_BM")), p -> String.valueOf(p.get("JE_META_UPGRADEPACKAGE_ID"))));
        if(source==null){
            source = new HashMap<>();
        }
        Set tableCodes = new HashSet();
        for(DynaBean funSource:funcs){
            DynaBean funcinfo = metaService.selectOne("JE_CORE_FUNCINFO",
                    ConditionsWrapper.builder().eq("JE_CORE_FUNCINFO_ID",funSource.getStr("UPGRADERESOURCE_CONTENT_CODE")));
            if(!source.containsKey(funcinfo.getStr("FUNCINFO_TABLENAME"))){
                tableCodes.add(funcinfo.getStr("FUNCINFO_TABLENAME"));
            }
        }
        importTableByTableCodes(tableCodes, upgradeId);
        return result;
    }

    public void importTableByTableCodes(Set tableCodes,String upgradeId){
        if(tableCodes==null || tableCodes.size()==0){
            return ;
        }
        List<DynaBean> list = metaService.select("JE_CORE_RESOURCETABLE",
                ConditionsWrapper.builder().in("RESOURCETABLE_TABLECODE",tableCodes));
        for(DynaBean table:list){
            DynaBean detailBean = new DynaBean("JE_META_UPGRADERESOURCE",false);
            detailBean.set("UPGRADERESOURCE_TYPE_NAME","资源表");
            detailBean.set("UPGRADERESOURCE_TYPE_CODE","table");
            detailBean.set("UPGRADERESOURCE_CONTENT_BM",table.getStr("RESOURCETABLE_TABLECODE"));
            detailBean.set("UPGRADERESOURCE_CONTENT_NAME",table.getStr("RESOURCETABLE_TABLENAME"));
            detailBean.set("UPGRADERESOURCE_CONTENT_CODE",table.getStr("JE_CORE_RESOURCETABLE_ID"));
            detailBean.set("JE_META_UPGRADEPACKAGE_ID",upgradeId);
            commonService.buildModelCreateInfo(detailBean);
            metaService.insert(detailBean);
        }
    }

    @Override
    public String saveResources(String oldId,String newId) {
        List<DynaBean> list = metaService.select("JE_META_UPGRADERESOURCE",ConditionsWrapper.builder()
                                .eq("JE_META_UPGRADEPACKAGE_ID",oldId));
        List<DynaBean> newList = new ArrayList<>();
        for(DynaBean dynaBean:list){
            dynaBean.setStr("JE_META_UPGRADERESOURCE_ID", JEUUID.uuid());
            dynaBean.setStr("JE_META_UPGRADEPACKAGE_ID",newId);
            commonService.buildModelCreateInfo(dynaBean);
            newList.add(dynaBean);
        }
        if(newList.size()>0){
            metaService.insertBatch(newList);
        }
        return null;
    }

    @Override
    public String getResourceIds(String upgradeId, String upgraderesourceType) {
        List<DynaBean> list = metaService.select("JE_META_UPGRADERESOURCE",
                ConditionsWrapper.builder().eq("UPGRADERESOURCE_TYPE_CODE",upgraderesourceType)
                                            .eq("JE_META_UPGRADEPACKAGE_ID",upgradeId).selectColumns("UPGRADERESOURCE_CONTENT_CODE"));
        if(list==null||list.size()==0){
            return "";
        }
        String ids = "";
        for(int i = 0;i<list.size();i++){
            DynaBean dynaBean = list.get(i);
            if(i==list.size()-1){
                ids+=dynaBean.getStr("UPGRADERESOURCE_CONTENT_CODE");
            }else{
                ids+=dynaBean.getStr("UPGRADERESOURCE_CONTENT_CODE")+",";
            }
        }
        return ids;
    }


    public void deleteResourceByType(String upgradeId,String type){
        metaService.delete("JE_META_UPGRADERESOURCE",
                ConditionsWrapper.builder().eq("JE_META_UPGRADEPACKAGE_ID",upgradeId).eq("UPGRADERESOURCE_TYPE_CODE",type));
    }

}
